package com.buanalintas.sandals.pos.stockshop;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Bynga;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.formatter.DateFormatter;
import com.buanalintas.bynga.formatter.NumberFormatter;
import com.buanalintas.bynga.generator.PageList;
import com.buanalintas.sandals.pos.entities.PosMasterItemStock;
import com.buanalintas.sandals.pos.entities.PosMasterStatus;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;

public class StockShop extends Page {

    private Field itemStockItemId;
    private Field itemStockValue;
    private Action actionShow = new Action("show", "Show stock");
    private Action actionExport = new Action("export", "Export stock");
    private static String MESSAGE_STATUS = "<!--MESSAGE-STATUS-->";
    private static String SELECT_STATUS_VALUES = "<!--SELECT-STATUS-VALUES-->";
    private static String RECAP_EXPORT = "RECAP-EXPORT";
    private static String RECAP_EXPORT_LINK = "<!--RECAP-EXPORT-LINK-->";
    private static String RECORD = "<!--RECORD-->";
    private static String LIST_DATA = "<!--LIST-DATA-->";
    private static String BUTTON_SEARCH = "<!--BUTTON-SEARCH-->";
    private NumberFormatter stockFormatter;

    public StockShop() {

        setTheClass(PosMasterItemStock.class);

        itemStockItemId = new Field();
        itemStockItemId.setName("itemStockItemId");
        itemStockItemId.setCaption("item");
        itemStockItemId.setListProperties(" align=\"left\" size=\"95%\"");
        itemStockItemId.setInputProperties("");
        getFields().add(itemStockItemId);

        itemStockValue = new Field();
        itemStockValue.setName("itemStockValue");
        itemStockValue.setCaption("stock");
        itemStockValue.setListProperties(" align=\"right\" size=\"5%\"");
        itemStockValue.setInputProperties(" ");
        getFields().add(itemStockValue);
        fillFields();
        
        getActions().add(actionShow);
        getActions().add(actionExport);
    }

    @Override
    public void afterInit(HttpServletRequest req, HttpServletResponse res) {
        itemStockItemId.setFormater(DateFormatter.getInstanceDate(this));
        stockFormatter = NumberFormatter.getInstance();
    }

    @Override
    public boolean isSearchVisible() {
        return false;
    }

    @Override
    public boolean isTitleVisible() {
        return false;
    }

    @Override
    public StringBuffer process() {
        if (getAction().equals(actionExport)) {

            try {
                updateExportParams();
                if ("2".equals(getCurrentUnit().getUnitName())) {
                    getResponse().setHeader("Content-Type", "application/vnd.ms-excel ");
                } else {
                    getResponse().setHeader("Content-Type", "application/pdf");
                }
                JRDataSource datasource = null;
                EntityManager em = getController().getEntityManager();
                PosMasterStatus status = null;
                String filter = Utility.getParameterEmpty(getRequest(), "status");
                System.out.println("-->" + filter);
                try {
                    status = (PosMasterStatus) getEntityManager().createQuery("SELECT t FROM PosMasterStatus t WHERE t.statusId='" + filter + "'").setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                    getExportParams().put("status", Utility.getParameterEmpty(getRequest(), "status") + " - " + status.getStatusName());
                } catch (Exception e) {
                    getExportParams().put("status", Utility.getParameterEmpty(getRequest(), "status"));
                }

                getExportParams().put("title", Dictionary.getValue(this, "Item Stock Status") + " #" + Dictionary.getValue(this, "Status"));
                if (!"".equals(filter)) {
                    getExportParams().put("filter", Dictionary.getValue(this, "Status") + " " + Utility.getPostParameterEmpty(this, "Status"));
                    getController().setWhere("t.itemStockStatusId.statusId='" + status.getStatusId() + "'AND t.itemStockUnitId.unitId=" + getCurrentUnit().getUnitId());
                    getController().setPaginationFilter("&status=" + filter);
                }
                datasource = new JRBeanArrayDataSource(getController().getData(true).toArray());
                JasperPrint jasperPrint = JasperFillManager.fillReport(getClass().getResourceAsStream("Stockshop.jasper"), getExportParams(), datasource);
                if ("2".equals(getCurrentUnit().getUnitName())) {
                    JRXlsExporter excelExporter = new JRXlsExporter();
                    excelExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
                    excelExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, getResponse().getOutputStream());
                    excelExporter.exportReport();
                } else {
                    JasperExportManager.exportReportToPdfStream(jasperPrint, getResponse().getOutputStream());
                }
                return null;

            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            return new StringBuffer();

        } else {
            StringBuffer content = Utility.load(Bynga.BYNGA_PACKAGE_THEME + "content.html");
            Template template = new Template();
            template.loadTemplate(getClass().getResourceAsStream("/com/buanalintas/sandals/pos/stockshop/template.html"));
            template.addValue(MESSAGE_STATUS, Dictionary.getValue(this, "Please select status"));

            EntityManager em = getEntityManager();

            StringBuffer selectStatus = new StringBuffer();
            String statusValue = Utility.getPostParameterEmpty(this, "status");
            Query query = em.createQuery("SELECT t FROM PosMasterStatus t ORDER BY t.statusName");
            for (Object object : query.getResultList()) {
                PosMasterStatus status = (PosMasterStatus) object;
                selectStatus.append("<option value=\"" + status.getStatusId() + "\"" + (statusValue.equals("" + status.getStatusId()) ? " selected" : "") + ">" + status.getStatusName() + "</option>");
            }
            template.addValue(SELECT_STATUS_VALUES, "" + selectStatus);

            if (!"".equals(statusValue)) {
                StringBuffer recapExportLink = template.getEmptyElement(RECAP_EXPORT);
                Utility.replaceAll(recapExportLink, RECAP_EXPORT_LINK, "?m=" + getMenu().getMenuName() + "&a=" + actionExport.getName() + "&status=" + statusValue);
                template.addElement(RECAP_EXPORT, recapExportLink);

                getController().setCondition("t.itemStockStatusId.statusId=" + statusValue + " AND t.itemStockUnitId.unitId=" + getCurrentUnit().getUnitId());
                template.addValue(RECORD, stockFormatter.format(getController().getCount()));
                template.addValue(LIST_DATA, PageList.process(this).toString());
            } else {
                template.addElement(RECAP_EXPORT, null);
            }

            template.addValue(BUTTON_SEARCH, Dictionary.getValue(this, "Search"));
            template.addValue(RECORD, null);

            Utility.replaceAll(content, Template.CONTENT_CONTENT, template.process().toString());
            updateContent(content, getMenu(), true);
            return content;
        }
    }

    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Stock Shop"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();

    }
}
